package com.yiwei.zhh.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.zhh.R;
import com.yiwei.zhh.api.Api;
import com.yiwei.zhh.api.bean.SaoMaBean;
import com.yiwei.zhh.util.DateTime;
import com.yiwei.zhh.util.Network;
import com.yiwei.zhh.util.QRCode;
import com.yiwei.zhh.util.RxLifeUtil;
import com.yiwei.zhh.util.ToastUtil;
import com.yiwei.zhh.util.UI;
import com.yiwei.zhh.view.V19FrameLayout;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/6/10.
 */

public class RepayQrcodeActivity extends BaseActivity {

    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_tips_one)
    TextView txtTipsOne;
    @BindView(R.id.txt_tips_two)
    TextView txtTipsTwo;
    @BindView(R.id.img_code)
    ImageView imgCode;
    @BindView(R.id.btn_refresh)
    TextView btnRefresh;
    @BindView(R.id.ll_code)
    LinearLayout llCode;
    @BindView(R.id.btn_save)
    SuperButton btnSave;
    @BindView(R.id.btn_alipay)
    SuperButton btnAlipay;
    @BindView(R.id.btn_wechat)
    SuperButton btnWechat;
    @BindView(R.id.txt_tips_one_sec)
    TextView txtTipsOneSec;
    @BindView(R.id.txt_code_type)
    TextView txtCodeType;
    @BindView(R.id.img_code_one)
    ImageView imgCodeOne;
    @BindView(R.id.txt_refresh_one)
    TextView txtRefreshOne;
    @BindView(R.id.layout_save)
    LinearLayout layoutSave;
    @BindView(R.id.img_refresh)
    ImageView imgRefresh;
    private Unbinder unbinder;
    private boolean isSaveSuccess;
    private String ACTION;
    private String deal_id;
    private String money;
    private String pay_type;
    private Bitmap wechat_bitmap;
    private Bitmap alipay_bitmap;
    private long now_time;
    private String yuqi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repay_qrcode);
        initBar();
        unbinder = ButterKnife.bind(this);
        init();
    }

    private void init() {
        ACTION = getIntent().getStringExtra("action");
        deal_id = getIntent().getStringExtra("deal_id");
        money = getIntent().getStringExtra("money");
        pay_type = getIntent().getStringExtra("pay_type");
//        if(pay_type.equals("0")){
//            btnAlipay.setTextColor(0xff616185);
//            btnAlipay.setShapeSolidColor(0xe6ffffff).setUseShape();
//            btnWechat.setTextColor(0xff4C81FF);
//            btnWechat.setShapeSolidColor(0xffffffff).setUseShape();
//        }else {
//            btnAlipay.setTextColor(0xff4C81FF);
//            btnAlipay.setShapeSolidColor(0xffffffff).setUseShape();
//            btnWechat.setTextColor(0xff616185);
//            btnWechat.setShapeSolidColor(0xe6ffffff).setUseShape();
//        }


        yuqi = getIntent().getStringExtra("yuqi");

        txtTipsOne.setText("￥" + money);
        txtTipsOneSec.setText("￥" + money);

        if (!TextUtils.isEmpty(yuqi)) {
            float benjin = Float.valueOf(money) - Float.valueOf(yuqi);
            txtTipsTwo.setText("本金" + benjin + "元+逾期" + yuqi + "元");
        }

        if (pay_type.equals("0")) {
            txtCodeType.setText("微信二维码");
        } else {
            txtCodeType.setText("支付宝二维码");
        }


        now_time = new Date().getTime();
//        btnRefresh.setText("请在" + DateTime.toShortTime(new Date().getTime() + 600000) + "前完成支付");
        getSaoMa();
    }

    @Override
    protected void onResume() {
        super.onResume();
        long time = new Date().getTime();
        if (time - now_time > 600000) {
            now_time = time;
            btnRefresh.setText("点击重置二维码");
            imgRefresh.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        unbinder = null;
    }

    public void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "zhh");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
        ToastUtil.makeText(context, "保存成功").show();
//        isSaveSuccess = true;
    }

    public static Bitmap loadBitmapFromView(View v) {
        if (v == null) {
            return null;
        }
        Bitmap screenshot;
        screenshot = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_4444);
        Canvas canvas = new Canvas(screenshot);
        canvas.translate(-v.getScrollX(), -v.getScrollY());//我们在用滑动View获得它的Bitmap时候，获得的是整个View的区域（包括隐藏的），如果想得到当前区域，需要重新定位到当前可显示的区域
        v.draw(canvas);// 将 view 画到画布上
        return screenshot;
    }

    public void getSaoMa() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();

        SaoMaBean bean = new SaoMaBean();
        bean.action = ACTION;
        bean.deal_id = deal_id;
        bean.money = money;
        bean.pay_type = pay_type;
        Api.api_service.getSaoMa(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();

                    } catch (NullPointerException e) {

                    }

                }).
                subscribe(result -> {
                    if (pay_type.equals("0")) {
                        wechat_bitmap = QRCode.createQRCode(result.data.qrcode_string);
                        imgCode.setImageBitmap(wechat_bitmap);
                        imgCodeOne.setImageBitmap(wechat_bitmap);

                    } else {
                        alipay_bitmap = QRCode.createQRCode(result.data.qrcode_string);
                        imgCode.setImageBitmap(alipay_bitmap);
                        imgCodeOne.setImageBitmap(alipay_bitmap);
                    }

                    UI.setTvHtml(txtRefreshOne, R.string.repay_time_tips, DateTime.toShortTime(new Date().getTime() + 600000));
//                    txtRefreshOne.setText("请在" + + "前完成支付");
                });
    }


    @OnClick({R.id.img_refresh, R.id.btn_refresh, R.id.btn_back, R.id.btn_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_refresh:
            case R.id.img_refresh:
                if(UI.toString(btnRefresh).equals("点击重置二维码")){
                    getSaoMa();
                }
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_save:
//                if (isSaveSuccess) {
//                    ToastUtil.makeText(this, "已保存成功");
//                    return;
//                }
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        saveImageToGallery(RepayQrcodeActivity.this, loadBitmapFromView(layoutSave));
                    }

                    @Override
                    public void superReject() {

                    }
                }, R.string.camera_storage_card_p, R.string.ask_again, Manifest.permission.WRITE_EXTERNAL_STORAGE);


                break;
        }
    }

    @OnClick({R.id.btn_alipay, R.id.btn_wechat})
    public void onViewClicked1(View view) {
        switch (view.getId()) {
            case R.id.btn_alipay:
                pay_type = "1";
                btnAlipay.setTextColor(0xff4C81FF);
                btnAlipay.setShapeSolidColor(0xffffffff).setUseShape();
                btnWechat.setTextColor(0xff616185);
                btnWechat.setShapeSolidColor(0xe6ffffff).setUseShape();
                if (pay_type.equals("0")) {
                    txtCodeType.setText("微信二维码");
                } else {
                    txtCodeType.setText("支付宝二维码");
                }

                if (alipay_bitmap != null) {
                    imgCode.setImageBitmap(alipay_bitmap);
                    imgCodeOne.setImageBitmap(alipay_bitmap);
                    return;
                }


                getSaoMa();
                break;
            case R.id.btn_wechat:
                pay_type = "0";
                btnAlipay.setTextColor(0xff616185);
                btnAlipay.setShapeSolidColor(0xe6ffffff).setUseShape();
                btnWechat.setTextColor(0xff4C81FF);
                btnWechat.setShapeSolidColor(0xffffffff).setUseShape();
                if (pay_type.equals("0")) {
                    txtCodeType.setText("微信二维码");
                } else {
                    txtCodeType.setText("支付宝二维码");
                }

                if (wechat_bitmap != null) {
                    imgCode.setImageBitmap(wechat_bitmap);
                    imgCodeOne.setImageBitmap(wechat_bitmap);
                    return;
                }
                getSaoMa();
                break;
        }
    }
}
